﻿using AutoMapper;
using B.S.Traceability.Domain;
using B.S.Traceability.Error;
using B.S.Traceability.Infrastructure.Interface;
using B.S.Traceability.Writer.API.Application.Commends.Health;
using MediatR;

namespace B.S.Traceability.Writer.API.Application.CommendHandlers.Health
{
    public class CreateHealthCommendHandlers : IRequestHandler<CreateHealthCommends, APIResult<Healths>>
    {

        private readonly IBaseRepository<Healths> healthsRepository;
        private readonly IMapper mapper;

        public CreateHealthCommendHandlers(IBaseRepository<Healths> healthsRepository, IMapper mapper)
        {
            this.healthsRepository = healthsRepository;
            this.mapper = mapper;
        }

        /// <summary>
        /// 添加保健信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<APIResult<Healths>> Handle(CreateHealthCommends request, CancellationToken cancellationToken)
        {
            APIResult<Healths> result = new APIResult<Healths>();

            var exit = healthsRepository.GetAllAsync().Result.FirstOrDefault(x => x.HealthId == request.HealthId);
            if (exit == null)
            {
                result.Code = APIEnum.添加成功;
                result.Msg = "添加成功";

                var farm = mapper.Map<Healths>(request);
                farm.BatchId = request.BatchId;
                farm.IsDel = false;
                await healthsRepository.Add(farm);

            }
            else
            {
                mapper.Map(request, exit);

                result.Code = APIEnum.修改成功;
                result.Msg = "修改成功";


                await healthsRepository.Update(exit);
            }
      

    
            return await Task.FromResult(result);
        }
    }
}
